package com.fiberhome.opticalbox.net.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;

import com.fiberhome.opticalbox.net.Constants;
import com.fiberhome.opticalbox.net.bean.data.VersionInfo;

/**
 * @author wangbin
 */
public class Util {

	/**
	 * @Title: checkNet
	 * @Description: Check the current net status.
	 * @param @param context
	 * @param @return
	 * @return boolean
	 * @throws
	 */
	public static boolean checkNet(Context context) {
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} catch (Exception e) {
		}
		return false;
	}

	public static InputStream getInputStream(String path) {
		URL url = null;
		InputStream is = null;
		try {
			url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			is = conn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}

	public static boolean checkSDCard() {
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}

	}

	public static int getScreenWidth(Activity activity) {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		return displayMetrics.widthPixels;
	}

	public static int getScreenHeight(Activity activity) {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		return displayMetrics.heightPixels;
	}

	public static void installOrUpdateApk(Context ctx, File apkFile) {
		Log.d("apk", "apk File = " + apkFile.toString());
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
		ctx.startActivity(intent);
	}

	public static void uninstallApk(Context ctx, String packageName) {
		Uri packageURI = Uri.parse("package:" + packageName);
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		ctx.startActivity(uninstallIntent);
	}

	public static boolean checkLoginName(String loginName) {
		Pattern pattern = Pattern.compile("[0-9a-zA-Z-]*");
		Matcher m = pattern.matcher(loginName);
		return m.matches();
	}

	public static boolean checkPassword(String password) {
		Pattern pattern = Pattern.compile("[0-9a-zA-Z-]*");
		Matcher m = pattern.matcher(password);
		return m.matches();
	}

	public static boolean checkNiceName(String niceName) {
		Pattern pattern = Pattern.compile("^[a-zA-Z0-9_\u4e00-\u9fa5]+$");
		Matcher m = pattern.matcher(niceName);
		return m.matches();
	}

	public static boolean checkEmail(String email) {
		Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		Matcher m = pattern.matcher(email);
		return m.matches();
	}

	public static String getTypeStr(int type) {
		switch (type) {
		case Constants.PHONE_APP_TYPE:
			return "�ֻ�Ӧ��";
		case Constants.GATEWAY_APP_TYPE:

			return "HGApplication";
		case Constants.GATEWAY_HG_TYPE:

			return "HGSystemFirmware";
		case Constants.GATEWAY_MEDIA_TYPE:

			return "HGMediaFile";
		}
		return null;
	}

	public static String getStatusStr(int status) {
		switch (status) {
		case 1:
			return "���ؿ�ʼ";
		case 2:
			return "�������";
		case 3:
			return "���������֤��";
		case 4:
			return "��֤��ɰ�װ��";
		case 5:
			return "��װ��� ";
		case 6:
			return "����ʧ��";
		case 7:
			return "��֤ʧ��";
		case 8:
			return "��װʧ��";
		case 9:
			return "���ӳ�ʱ��������";
		}
		return null;
	}

	@SuppressLint("SimpleDateFormat")
	public static String formatDate(String time) {
		StringBuffer bufferTime = new StringBuffer();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = null;
		try {
			date = sdf.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);

		bufferTime.append(c.get(Calendar.YEAR)).append("��").append(c.get(Calendar.MONTH) + 1).append("��")
				.append(c.get(Calendar.DAY_OF_MONTH)).append("��");
		return bufferTime.toString();

	}

	public static String getServerIp(Context context) {
		SharedPreferences settings = context.getSharedPreferences(Constants.SETTINGS_SHAREDPREFERENCE, Context.MODE_PRIVATE);
		return settings.getString("setting_Ip", "http://10.96.16.16:80");
	}

	/**
	 * �Ƿ�װӦ��
	 * 
	 * @param context
	 * @param packagename
	 * @return
	 */
	public static boolean isInstalled(Context context, String packagename) {
		PackageInfo packageInfo = null;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);

		} catch (NameNotFoundException e) {
			packageInfo = null;
		}

		if (packageInfo != null) {
			return true;
		} else {
			return false;
		}
	}

	public static void openApplication(Context context, String packageName) {
		Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
		context.startActivity(intent);
	}

	// ȥ��wan������
	public static String[] filterBrige(String[] input) {
		if (input == null || input.length == 0) {
			return null;
		}
		List<String> ret = new ArrayList<String>();
		for (String s : input) {
			if (s.indexOf("_B_") > -1 || s.indexOf("_b_") > -1) {
				continue;
			}
			ret.add(s);
		}

		String[] out = new String[ret.size()];
		return ret.toArray(out);
	}

	public static String readInputstream(InputStream in) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder builder = new StringBuilder();
		try {
			String out = "";
			while ((out = reader.readLine()) != null) {
				builder.append(out);
				if (out.contains("return_Parameter")) {
					builder.append("}");
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
				reader = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return builder.toString();
	}

	/**
	 * @Title: get update apk information
	 * @throws
	 */
	public static VersionInfo getUpdateInfo(InputStream in) {
		try {
			String json = Util.readInputstream(in);
			System.out.println("url response " + json);
			VersionInfo info = new VersionInfo();
			JSONObject object = new JSONObject(json);
			String result = object.getString("Result");
			String desc = object.getString("statement");
			String downloadUrl = object.getString("download_url");
			info.setResult(result);
			info.setDesc(desc);
			info.setDownloadUrl(downloadUrl);
			return info;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
